<template>
  <div class="app-container">
    <div id="addEditEvent" class="container-fluid add-page addEdit">
      <el-form ref="info" :model="info" :rules="rules">
        <el-row :gutter="20" class="solid-row">
          <el-col :sm="20" :md="20" :lg="14" :xl="14">
            <el-form-item prop="activities">
              <div class="ul-input">
                <label class="label-md cur">Activities:</label>
                <el-select v-model="info.activities" placeholder="Select"><el-option v-for="item in ActivitiesList" :key="item.value" :label="item.typeName" :value="item.id" /></el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col :sm="20" :md="20" :lg="14" :xl="14">
            <el-form-item prop="levelMenu">
              <div class="ul-input">
                <label class="label-md">Level:</label>

                <el-select v-model="info.levelMenu" placeholder="Select">
                  <el-option v-for="item in LevelMenulist" :key="item.value" :label="item.typeName" :value="item.id" />
                </el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col :sm="20" :md="20" :lg="14" :xl="14">
            <el-form-item prop="competition">
              <div class="ul-input">
                <label class="label-md">Competition:</label>
                <input v-model="info.competition">
              </div>
            </el-form-item>
          </el-col>
          <el-col :sm="20" :md="20" :lg="14" :xl="14">
            <el-form-item prop="eventName">
              <div class="ul-input">
                <label class="label-md">比賽名稱:</label>
                <input v-model="info.eventName">
              </div>
            </el-form-item>
          </el-col>
          <el-col :sm="20" :md="20" :lg="14" :xl="14">
            <el-form-item prop="location">
              <div class="ul-input">
                <label class="label-md">Location:</label>
                <input v-model="info.location">
              </div>
            </el-form-item>
          </el-col>
          <el-col :sm="20" :md="20" :lg="14" :xl="14">
            <el-form-item prop="tcLocation">
              <div class="ul-input">
                <label class="label-md">比賽地點:</label>
                <input v-model="info.tcLocation">
              </div>
            </el-form-item>
          </el-col>
          <el-col :sm="20" :md="20" :lg="14" :xl="14" class="ul-input">
            <div class="ul-input" style="justify-content: flex-start;width: 50%;">
              <label class="label-md">Date Start:</label>
              <el-form-item v-show="false" prop="startDate" style="margin: 0;width: auto;"><el-input v-model="info.startDate" /></el-form-item>
              <el-date-picker v-model="info.startDate" placeholder="Date Picker" format="dd-MM-yyyy" value-format="yyyy-MM-dd" style="width: 100%;" />
            </div>

            <div class="ul-input" style="justify-content: flex-start;width: 50%;">
              <label class="label-md">Date End:</label>
              <el-form-item v-show="false" prop="endDate" style="margin: 0;width: auto;"><el-input v-model="info.startDate" /></el-form-item>
              <el-date-picker v-model="info.endDate" placeholder="Date Picker" format="dd-MM-yyyy" value-format="yyyy-MM-dd" />
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="solid-row">
          <el-col :sm="14" :md="14" :lg="10" :xl="10">
            <el-form-item prop="eventWebsite" style="width: auto;">
              <div class="ul-input">
                <label class="label-md">Event Website:</label>
                <el-input v-model="info.eventWebsite" />
                <!-- <button type="button" class="el-button el-button--success" @click="addhelerList(helerListData.name, helerListData.id)"><span>Add</span></button> -->
              </div>
            </el-form-item>
          </el-col>

          <el-col :sm="24" :md="24" :lg="24" :xl="24">
            <div v-for="(item, i) in coachListData.list" :key="item.key" style="display: inline-block;position: relative;margin-right: 20px">
              <img src="../../assets/images/del2.svg" class="btn-icon-del" alt="delete" @click="delFollowUp(i, 'CoachList')">
              <div class="ul-input"><input :value="item.name" readonly></div>
            </div>
          </el-col>
          <el-col :sm="20" :md="20" :lg="14" :xl="14">
            <div class="ul-input" style="height: 40px;pajustify-content: center;">
              <el-form-item prop="countdown" style="margin: 0;width:40%;" label="Countdown:">
                <el-checkbox v-model="info.countdown" :true-label="1" :false-label="0" style="padding-left: 10px;text-align: left" />
              </el-form-item>
              <el-form-item prop="remarks" class="ul-input" style="margin: 0;width:40%;" label="Remarks:">
                <el-input v-model="info.remarks"  style="padding-left: 10px;text-align: left" />
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-form-item style="margin: 0;text-align: center;" class="button">
          <router-link to="/event"><el-button type="success" size="medium">Back</el-button></router-link>
          <el-button type="success" size="medium" @click="onSubmit('info')">{{ info.id ? 'Save' : 'Add' }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { getBelongingTypes, queryAthletesList, queryUserList } from '@/api/setting'
import { addEvent, modifyEvent, getEventInfo } from '@/api/event'
const nowDate = new Date()
export default {
  data() {
    return {
      athleteData: {
        name: '',
        id: '',
        list: []
      },
      helerListData: {
        name: '',
        id: '',
        list: []
      },
      coachListData: {
        name: '',
        id: '',
        list: []
      },
      info: {
        activities: '',
        levelMenu: '',
        competition: '',
        startDate: `${nowDate.getFullYear()}-${nowDate.getMonth() + 1}-${nowDate.getDate()}`,
        endDate: `${nowDate.getFullYear()}-${nowDate.getMonth() + 1}-${nowDate.getDate() + 1}`,
        countdown: '',
        eventName: '',
        location: '',
        tcLocation: '',
        eventWebsite: '',
        remarks: ''
      },
      LevelMenulist: [],
      ActivitiesList: [],
      rules: {
        activities: [{ required: true, message: 'Activities cannot be empty', trigger: 'blur' }],
        levelMenu: [{ required: true, message: 'LevelMenu cannot be empty', trigger: 'blur' }],
        competition: [{ required: true, message: 'Competition cannot be empty', trigger: 'blur' }],

        eventName: [{ required: true, message: '比賽名稱 cannot be empty' }],

        location: [{ required: true, message: 'Location cannot be empty', trigger: 'blur' }],
        tcLocation: [{ required: true, message: '比賽地點 cannot be empty', trigger: 'blur' }],
        startDate: [
          { required: true, message: 'StartDate cannot be empty', trigger: 'blur' }],
        endDate: [{ required: true, message: 'EndDate cannot be empty', trigger: 'blur' }]
        // countdown: [
        //     { required: true, message: 'Activities cannot be empty', trigger: 'blur' }
        // ]
        // eventWebsite: [
        //     { required: true, message: 'Activities cannot be empty', trigger: 'blur' }
        // ],
        // remarks: [
        //     { required: true, message: 'Activities cannot be empty', trigger: 'blur' }
        // ]
      }
    }
  },
  created() {
    const query = this.$route.query
    if (query.id) {
      this.getInfo(query.id)
    }
    this.fetchData()
  },
  methods: {
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
      let t1 =   new Date(this.info.startDate).getTime(), t2 = new Date(this.info.endDate).getTime()
      var isTimeTure =  t1<t2
        
        if (valid) {
          if(!isTimeTure){
            return this.$message({type:'warning',message:'End time cannot be less than start time!'})
          }
          const params = {}
          Object.assign(params, this.info)
         // params.countdown = params.countdown ? 1 : 0
          // params.helerList = JSON.stringify(this.helerListData.list)
          // params.coachList = JSON.stringify(this.coachListData.list)
          // if (!params.event) {
          //     this.$message({
          //         type: 'error',
          //         message: 'Please event input'
          //     })
          //     return false
          // }
          this.openLoading(true)
          // if (params.id) {
          //   modifyEvent(params).then(response => {
          //     // eslint-disable-next-line no-unused-vars
          //     const data = response.result
          //     if (response.status === 0) {
          //       data.countdown = data.countdown === '1'
          //       this.info = data
          //       this.$message({
          //         type: 'success',
          //         message: response.msg
          //       })
          //     }
          //     this.openLoading(false)
          //   })
          // } else {
            addEvent(params).then(
              response => {
                // eslint-disable-next-line no-unused-vars
                const data = response.result
                if (response.status === 0) {
                  const data = response.result

                    this.$router.push({ path: `/event` })

                }
                this.openLoading(false)
              },
              error => {
                this.openLoading(false)
              }
            )
          // }
        } else {
        }
      })
    },
    queryAthleteSearchAsync(queryString, cb) {
      if (queryString === '') {
        cb([])
        return false
      }
      var restaurants = this.restaurants
      queryAthletesList({ name: queryString }).then(response => {
        // var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants
        var results = []
        var data = response.result
        for (var i in data) {
          results.push({
            value: data[i].lastName + ' ' + data[i].firstName,
            name: data[i].lastName + ' ' + data[i].firstName,
            id: data[i].userId
          })
        }
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          cb(results)
        }, 200 * Math.random())
      })
    },
    querySearchAsync(queryString, cb) {
      if (queryString === '') {
        cb([])
        return false
      }
      var restaurants = this.restaurants
      queryUserList({ name: queryString }).then(response => {
        // var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants
        var results = []
        var data = response.result
        for (var i in data) {
          results.push({
            value: data[i].lastName + ' ' + data[i].firstName,
            name: data[i].lastName + ' ' + data[i].firstName,
            id: data[i].userId
          })
        }
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          cb(results)
        }, 200 * Math.random())
      })
    },
    createStateFilter(queryString) {
      return state => {
        return state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      }
    },
    addhelerList(name, id, type) {
      if (name && id) {
        if (type === 'CoachList') {
          const list = this.coachListData.list
          list.push({ name: name, id: id })
          this.coachListData.name = ''
          this.coachListData.id = ''
        } else {
          const list = this.helerListData.list
          list.push({ name: name, id: id })
          this.helerListData.name = ''
          this.helerListData.id = ''
        }
      }
    },
    athleteshandleSelect(item) {
      this.helerListData.name = item.name
      this.helerListData.id = item.id
    },
    coachListSelect(item) {
      this.coachListData.name = item.name
      this.coachListData.id = item.id
    },
    delFollowUp(key, type) {
      if (type === 'CoachList') {
        const list = this.coachListData.list
        list.splice(key, 1)
      } else {
        const list = this.helerListData.list
        list.splice(key, 1)
      }
    },
    fetchData() {
      getBelongingTypes({ belonging: 'EVENT' }).then(response => {
        const data = response.result
        this.ActivitiesList = data.ACTIVITIES_EVENT
        this.LevelMenulist = data.COMPETIOTION
      })
    },
    getInfo(id) {
      getEventInfo({ eventId: id }).then(response => {
        const data = response.result
        // if (data.countdown) {
        //   data.countdown = true
        // } else {
        //   data.countdown = false
        // }
        // data.matchClass = data.matchClass || ''
        // data.types = data.types || ''
        const {
          id,
          activities,
          levelMenu,
          competition,
          startDate,
          endDate,
          countdown,
          eventName,
          location,
          tcLocation,
          eventWebsite,
          remarks
        } = data

        this.info = {
          id,
          activities,
          levelMenu,
          competition,
          startDate,
          endDate,
          countdown: countdown || 0,
          eventName,
          location,
          tcLocation,
          eventWebsite,
          remarks:remarks
        }
      })

    },
    openLoading(type, text) {
      const loading = this.$loading()
      if (type) {
        this.$loading({
          lock: true,
          text: text || 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0)'
        })
        setTimeout(() => {
          loading.close()
        }, 10000)
      } else {
        setTimeout(() => {
          loading.close()
        }, 500)
      }
    }
  },
  beforeRouteLeave(to, from, next) {
    // this.$confirm('Do you really want to leave? you have unsaved changes?', '提示', {
    //     confirmButtonText: 'Yes',
    //     cancelButtonText: 'ON',
    //     type: 'warning'
    // }).then(() => {
    //     next()
    // }).catch(() => {
    //     next(false)
    // })
    next()
  }
}
</script>
<style lang="scss">
  #addEditEvent{
    .el-table th.gutter {
      display: table-cell !important;
    }

  }
    .addEdit .el-button {
      margin: 0 5px;
    }
</style>
